package com.aliothservice.catfish.admin;

import java.net.SocketAddress;
import java.util.concurrent.TimeUnit;

import org.springframework.data.redis.core.RedisTemplate;

import com.aliothservice.catfish.device.CollectorInboundAdapter;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;

public class MockupOutboundAdapter extends ChannelOutboundHandlerAdapter {
	
	public static final String REQUEST_TYPE_HEARTBEAT = "heartbeat";

	@Override
	public void connect(ChannelHandlerContext context, SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) {
		if (0 == this.getReqType().compareTo(REQUEST_TYPE_HEARTBEAT)) {
			final ByteBuf reqBuffer = context.alloc().buffer(16);
			reqBuffer.writeBytes(this.getDeviceSN().getBytes());
			reqBuffer.writeInt(0);
			reqBuffer.writeShort(CollectorInboundAdapter.CMD_HEARTBEAT);
			reqBuffer.writeShort(0);
			final ChannelFuture writeFuture = context.writeAndFlush(reqBuffer);
			writeFuture.addListener(ChannelFutureListener.CLOSE);
			String reqDump = "REQUEST_HEADER {SN: " + this.getDeviceSN() +", Body Length: 0, Command: 0 (heartbeat), Reserved: 0}";
			redisTemplate.opsForValue().set(this.getReceipt()+"_outbound", reqDump, 5, TimeUnit.MINUTES);
		}
	}
	
	public String getReceipt() {
		return receipt;
	}

	public void setReceipt(String receipt) {
		this.receipt = receipt;
	}

	public String getReqType() {
		return reqType;
	}

	public void setReqType(String reqType) {
		this.reqType = reqType;
	}

	public RedisTemplate<String, Object> getRedisTemplate() {
		return redisTemplate;
	}

	public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
		this.redisTemplate = redisTemplate;
	}

	public String getDeviceSN() {
		return deviceSN;
	}

	public void setDeviceSN(String deviceSN) {
		this.deviceSN = deviceSN;
	}

	private String deviceSN;
	
	private String receipt;
	
	private String reqType;
	
	private RedisTemplate<String, Object> redisTemplate;
}
